package org.grayrabbit.cms.publish.gc;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.grayrabbit.cms.publish.generate.factory.AbstractFactory;


public class PublishTaslGC implements Runnable{
	private static boolean running = false;
	private static final PublishTaslGC P_GC = new PublishTaslGC();
	public static void start(){
		if(!running){
			synchronized (PublishTaslGC.class) {
				if(!running){//双重判断
					Thread gc = new Thread(P_GC);
					gc.setDaemon(true);
					gc.start();
					running = true;
				}
			}
		}
	}
	public void run() {
		while(true){
			try {
				Thread.sleep(5 * 60 * 1000);//5分钟清除一次
				clear();
			} catch (InterruptedException e) {
			}
		}
	}
	
	private void clear(){
		long now =(new Date()).getTime();
		synchronized (AbstractFactory.LOCK) {
			Map<String,Integer> map = new HashMap<String, Integer>();
			for(String key :AbstractFactory.percent.keySet()){
				if(key.endsWith(AbstractFactory.TIME)){
					long time = AbstractFactory.percent.get(key).longValue();
					if(!isTimeOut(now,time)){
						String preKey = key.substring(0, key.length() - 4);
						map.put(preKey +AbstractFactory.TOTAL, AbstractFactory.percent.get(preKey +AbstractFactory.TOTAL));
						map.put(preKey +AbstractFactory.FAIL, AbstractFactory.percent.get(preKey +AbstractFactory.FAIL));
						map.put(preKey +AbstractFactory.FINISHED, AbstractFactory.percent.get(preKey +AbstractFactory.FINISHED));
					}
				}
			}
			AbstractFactory.percent.clear();
			for(String key : map.keySet()){
				AbstractFactory.percent.put(key, map.get(key));
			}
		}
	}
	
	private final long MAX = 30 * 60 * 1000;
	private boolean isTimeOut(long now,long time){
		long det = now - time;
		if(det > MAX){
			return true;
		}
		return false;
	}

}
